package com.util;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

/**
 * @author tj
 */
public class DBControl {
	private SQLiteDatabase g_easy_do_db = null;

	public DBControl(Context context) {
		OpenDataBase(context);
	}

	public boolean OpenDataBase(Context context) {
		if (g_easy_do_db == null) {
			g_easy_do_db = context.openOrCreateDatabase("collect.db",
					Context.MODE_PRIVATE, null);
			/*
			 * g_easy_do_db = context.openOrCreateDatabase(
			 * Environment.getExternalStorageDirectory().getAbsolutePath() +
			 * "/lehuo/collect.db", Context.MODE_PRIVATE, null);
			 */
		}
		/*
		 * LocalExecuteUpdate(
		 * "CREATE TABLE IF NOT EXISTS collect (id integer primary key autoincrement,"
		 * +
		 * "title text,time text,img_url text,content_url text,type integer)");
		 */

		LocalExecuteUpdate("CREATE TABLE IF NOT EXISTS collects (id integer primary key autoincrement,"
				+ "title text,time text,img_url text,content_url text,telephone text,type integer,user_id text,"
				+ "bak0 text,bak1 text,bak2 text,bak3 text)");

		LocalExecuteUpdate("CREATE TABLE IF NOT EXISTS imagetext (id integer primary key autoincrement,category integer,commid integer,"
				+ "contenturl text,itemdisptype integer,itemid integer,itemname text,itempicurl text,itemsort integer,telephone text,"
				+ "group_type integer,bak0 text,bak1 text,bak2 text,bak3 text)");

		return true;
	}

	public boolean GetDataFromLocalDB(ArrayList<JSONObject> array, String sql) {
		Cursor result = g_easy_do_db.rawQuery(sql, null);
		int count = result.getColumnCount();
		while (result.moveToNext()) {
			JSONObject obj = new JSONObject();
			for (int i = 0; i < count; i++) {
				try {
					String key = result.getColumnName(i);
					obj.put(key, result.getString(i));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			array.add(obj);
		}

		result.close();
		return true;
	}

	public boolean GetDataFromLocalDB2Dictionary(JSONObject obj, String sql) {
		Cursor result = g_easy_do_db.rawQuery(sql, null);
		int count = result.getColumnCount();

		if (result.getCount() == 1) {
			result.moveToFirst();
			for (int i = 0; i < count; i++) {
				String key = result.getColumnName(i);
				try {
					obj.put(key, result.getString(i));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

		result.close();
		return true;
	}

	public String GetSelectStringByKey(String sql) {
		String res = "";
		Cursor result = g_easy_do_db.rawQuery(sql, null);
		if (result.getCount() > 0) {
			result.moveToFirst();
			res = result.getString(0);
		}

		result.close();
		return res;
	}

	public boolean LocalExecuteUpdate(String sql) {
		g_easy_do_db.execSQL(sql);
		return true;
	}
}